import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'package:test1/View/MyRowText.dart';

class Flutter_Net_Http_Page extends StatelessWidget with RequestCallBack {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Http"),
        ),
        body: Container(
            color: Color(0xfff1f1f1),
            child: ListView(
              children: <Widget>[
                MyRowText(
                    "post",
                    () => doRequest(
                        "https://free-api.heweather.com/s6/weather/now?parameters",
                        {
                          'location': '北京',
                          'key': 'eaf572c8304f4eeb8ad209bf05da2872'
                        },
                        this)),
                MyRowText(
                    "get",
                    () => doRequest2(
                        "http://api.douban.com/v2/movie/top250?start=0&count=5",
                        this)),
              ],
            )),
      ),
    );
  }

  /**
   * 网络调用通常遵循如下步骤：
      创建 client.
      构造 Uri.
      发起请求, 等待请求，同时您也可以配置请求headers、 body。
      关闭请求, 等待响应.
      解码响应的内容.
   */

  void doRequest(String url, Map<String, dynamic> map,
      RequestCallBack requestCallBack) async {
    var client = http.Client();

    client.post(Uri(path: url), body: map).then((response) {
      requestCallBack.onSuccess(response.body);
    }).catchError((error) {
      requestCallBack.onError();
    }).whenComplete(
      client.close,
    );
  }

  void doRequest2(String url, RequestCallBack requestCallBack) async {
    var client = http.Client();

    client.get(Uri(path: url)).then((response) {
      requestCallBack.onSuccess(response.body);
    }).catchError((error) {
      requestCallBack.onError();
    }).whenComplete(
      client.close,
    );
  }

  @override
  void onError() {}

  @override
  void onSuccess(String result) {
    print(result);
  }
}

abstract class RequestCallBack {
  void onSuccess(String result);

  void onError();
}
